package com.ysd.lis.service.lab.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.lis.entity.SysOrgDepartment;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.bac.BacTestResult;
import com.ysd.lis.entity.lab.*;
import com.ysd.lis.mapper.lab.LabItemDictMapper;
import com.ysd.lis.mapper.lab.LabMaininfoMapper;
import com.ysd.lis.request.lab.ReportExportExcelParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class LabMaininfoExcelServiceImpl extends ServiceImpl<LabItemDictMapper, LabItemDict> {
    @Autowired
    LabMaininfoMapper labMaininfoMapper;
    // 定义一个map
    private final static Map<String, String> sexMap = new HashMap<String, String>() {{
        put("1", "男");
        put("2", "女");
        put("3", "未知");
    }};
    private final static Map<String, String> flagMap = new HashMap<String, String>() {{
        put("H", "↑");
        put("L", "↓");
        put("P", "+");
        put("Q", "±");
        put("N", "-");
        put("E", "×");
    }};


    public void ExportExcel(ReportExportExcelParam reportExportExcelParam, HttpServletResponse response) {
        HSSFWorkbook workbook = null;
        try {
            workbook = new HSSFWorkbook();

            HSSFCellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            // 创建工作表
            Sheet sheet = workbook.createSheet("报告查询");

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            // 创建第0列，其赋值为Cell类
            for (int i = 0; i < 22; i++) {
                Cell headerCell1 = headerRow.createCell(i);

                // 通过该类赋值其含义，此为第0列的属性
                if (i == 0) {
                    headerCell1.setCellValue("报告单元");
                    sheet.setColumnWidth(i, 12 * 256);
                }
                if (i == 1) {
                    headerCell1.setCellValue("检验日期");
                    sheet.setColumnWidth(i, 10 * 256);
                }
                if (i == 2) {
                    headerCell1.setCellValue("姓名");
                    sheet.setColumnWidth(i, 10 * 256);
                }
                if (i == 3) {
                    headerCell1.setCellValue("性别");
                    sheet.setColumnWidth(i, 5 * 256);
                }
                if (i == 4) {
                    headerCell1.setCellValue("年龄");
                    sheet.setColumnWidth(i, 8 * 256);
                }
                if (i == 5) {
                    headerCell1.setCellValue("病床");
                    sheet.setColumnWidth(i, 10 * 256);
                }
                if (i == 6) {
                    headerCell1.setCellValue("病历号");
                    sheet.setColumnWidth(i, 20 * 256);
                }
                if (i == 7) {
                    headerCell1.setCellValue("申请目的");
                    sheet.setColumnWidth(i, 35 * 256);
                }
                if (i == 8) {
                    headerCell1.setCellValue("样本类型");
                    sheet.setColumnWidth(i, 10 * 256);
                }
                if (i == 9) {
                    headerCell1.setCellValue("科室");
                    sheet.setColumnWidth(i, 20 * 256);
                }
                if (i == 10) {
                    headerCell1.setCellValue("条码号");
                    sheet.setColumnWidth(i, 15 * 256);
                }
                if (i == 11) {
                    headerCell1.setCellValue("病人类型");
                    sheet.setColumnWidth(i, 10 * 256);
                }
                if (i == 12) {
                    headerCell1.setCellValue("标本号");
                    sheet.setColumnWidth(i, 8 * 256);
                }
                if (i == 13) {
                    headerCell1.setCellValue("上机时间");
                    sheet.setColumnWidth(i, 15 * 256);
                }
                if (i == 14) {
                    headerCell1.setCellValue("打印人");
                    sheet.setColumnWidth(i, 10 * 256);
                }
                if (i == 15) {
                    headerCell1.setCellValue("打印时间");
                    sheet.setColumnWidth(i, 15 * 256);
                }
                if (i == 16) {
                    headerCell1.setCellValue("打印次数");
                    sheet.setColumnWidth(i, 10 * 256);
                }
                if (i == 17) {
                    headerCell1.setCellValue("检验项目");
                    sheet.setColumnWidth(i, 30 * 256);
                }
                if (i == 18) {
                    headerCell1.setCellValue("检验结果");
                    sheet.setColumnWidth(i, 10 * 256);
                }
                if (i == 19) {
                    headerCell1.setCellValue("");
                    sheet.setColumnWidth(i, 4 * 256);
                }
                if (i == 20) {
                    headerCell1.setCellValue("参考范围");
                    sheet.setColumnWidth(i, 15 * 256);
                }
                if (i == 21) {
                    headerCell1.setCellValue("单位");
                    sheet.setColumnWidth(i, 10 * 256);
                }
                headerCell1.setCellStyle(cellStyle);
            }

            String idsStr = reportExportExcelParam.getIds().isEmpty() ? "!@#QWE!@#" : reportExportExcelParam.getIds().stream().collect(Collectors.joining("','"));

            MPJLambdaWrapper<LabMaininfo> queryWrapper = new MPJLambdaWrapper<>();
            queryWrapper.selectAll(LabMaininfo.class);
            queryWrapper.eq(LabMaininfo::getDelFlag, 0);
            queryWrapper.selectAs("rptresult", LabRptresultQ::getItemNa, LabMaininfo::getItemNa);
            queryWrapper.selectAs("rptresult", LabRptresultQ::getItemNo, LabMaininfo::getItemNo);
            queryWrapper.selectAs("rptresult", LabRptresultQ::getTestResult, LabMaininfo::getResult);
            queryWrapper.selectAs("rptresult", LabRptresultQ::getResultFlag, LabMaininfo::getResultFlag);
            queryWrapper.selectAs("rptresult", LabRptresultQ::getRef, LabMaininfo::getRef);
            queryWrapper.selectAs("itemdict", LabItemDict::getUnit, LabMaininfo::getUnit);
            queryWrapper.selectAs("itemdict", LabItemDict::getSeq, LabMaininfo::getSeq);
            queryWrapper.selectAs("reqDept", SysOrgDepartment::getName, LabMaininfo::getReqDeptNa);
            queryWrapper.selectAs("printDocter", SysUser::getRealname, LabMaininfo::getPrintDoctorNa);
            queryWrapper.selectAs("rptgptna", LabRptGroup::getRptGroupName, LabMaininfo::getRptGroupNa);
            // queryWrapper.in(LabMaininfo::getId, ids);
            queryWrapper.inSql(LabMaininfo::getId, "select ID from LAB_MAININFO where ID in ('" + idsStr + "')");
            queryWrapper.leftJoin(LabRptresultQ.class, "rptresult", p -> p.eq(LabMaininfo::getSampleNo, LabRptresultQ::getSampleNo).isNotNull(LabRptresultQ::getSampleNo).ne(LabRptresultQ::getSampleNo, "").eq(LabMaininfo::getSampleda, LabRptresultQ::getSampleda).isNotNull(LabRptresultQ::getSampleda).eq(LabMaininfo::getRptGroup, LabRptresultQ::getRptGroup).isNotNull(LabRptresultQ::getRptGroup).ne(LabRptresultQ::getRptGroup, "").eq(LabRptresultQ::getDelFlag, 0));
            queryWrapper.leftJoin(LabItemDict.class, "itemdict", p -> p.eq(LabRptresultQ::getRptGroup, LabItemDict::getRptGroup).eq(LabRptresultQ::getItemNo, LabItemDict::getItemNo).isNotNull(LabItemDict::getRptGroup).isNotNull(LabItemDict::getItemNo).ne(LabItemDict::getRptGroup, "").ne(LabItemDict::getItemNo, "").eq(LabItemDict::getDelFlag, 0));
            queryWrapper.leftJoin(LabRptGroup.class, "rptgptna", p -> p.eq(LabMaininfo::getRptGroup, LabRptGroup::getRptGroup).eq(LabRptGroup::getDelFlag, 0).isNotNull(LabRptGroup::getRptGroup).ne(LabRptGroup::getRptGroup, ""));
            queryWrapper.leftJoin(SysOrgDepartment.class, "reqDept", p -> p.eq(LabMaininfo::getReqDept, SysOrgDepartment::getCode).eq(SysOrgDepartment::getDelFlag, 0).isNotNull(SysOrgDepartment::getCode).ne(SysOrgDepartment::getCode, ""));
            queryWrapper.leftJoin(SysUser.class, "printDocter", p -> p.eq(LabMaininfo::getPrintDoctor, SysUser::getUsername).eq(SysUser::getDelFlag, 0).isNotNull(SysUser::getUsername).ne(SysUser::getUsername, ""));
            // queryWrapper.orderByAsc("sampleda", "SAMPLE_NO", "seq");
            List<LabMaininfo> list1 = labMaininfoMapper.selectList(queryWrapper);
            List<LabMaininfo> list = list1.stream().sorted(Comparator.comparing(LabMaininfo::getId, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getSampleNo, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getSeq, Comparator.nullsLast(Comparator.naturalOrder()))).collect(Collectors.toList());

            if (!list.isEmpty()) {
                //{
                // List<LabMaininfo> lstArr=mm.getValue();
                //}
                // maps.forEach((id, lstArr) ->
                // Map<String, List<LabMaininfo>> maps = list.stream().collect(Collectors.groupingBy(LabMaininfo::getId));
                int i = 1;
                for (LabMaininfo m : list) {
                    Row dataRow1 = sheet.createRow(i);
                    for (int j = 0; j < 22; j++) {
                        Cell dataCell1 = dataRow1.createCell(j);
                        if (j == 0) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getRptGroupNa()) ? m.getRptGroupNa() : "");
                        }
                        if (j == 1) {
                            if (BeanUtil.isNotEmpty(m.getSampleda())) {
                                Timestamp timestamp = new Timestamp(m.getSampleda().getTime());
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                String formattedDate = sdf.format(timestamp);
                                dataCell1.setCellValue(formattedDate);// StringUtils.isNotBlank(m.getSampleda()) ? m.getSampleda() : "");
                            } else {
                                dataCell1.setCellValue("");
                            }
                        }
                        if (j == 2) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getPatNa()) ? m.getPatNa() : "");
                        }
                        if (j == 3) {
                            String sexStr = "";
                            if ("1".equals(m.getSex())) {
                                sexStr = "男";
                            }
                            if ("2".equals(m.getSex())) {
                                sexStr = "女";
                            }
                            if ("3".equals(m.getSex())) {
                                sexStr = "未知";
                            }
                            dataCell1.setCellValue(StringUtils.isNotBlank(sexStr) ? sexStr : "");
                        }
                        if (j == 4) {
                            String ageStr = "";
                            if (BeanUtil.isNotEmpty(m.getAge())) {
                                ageStr += m.getAge().toString();
                            }
                            if (StringUtils.isNotBlank(m.getAgeUnit())) {
                                ageStr += m.getAgeUnit().toString();
                            }
                            if (BeanUtil.isNotEmpty(m.getSecAge())) {
                                ageStr += m.getSecAge().toString();
                            }
                            if (StringUtils.isNotBlank(m.getSecAgeUnit())) {
                                ageStr += m.getSecAgeUnit().toString();
                            }
                            dataCell1.setCellValue(StringUtils.isNotBlank(ageStr) ? ageStr : "");
                        }
                        if (j == 5) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getBedNo()) ? m.getBedNo() : "");// StringUtils.isNotBlank(m.getAge()) ? m.getAge() : "");
                        }
                        if (j == 6) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getPatNo()) ? m.getPatNo() : "");
                        }
                        if (j == 7) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getReqPurpose()) ? m.getReqPurpose() : "");
                        }
                        if (j == 8) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getSampleTypeNa()) ? m.getSampleTypeNa() : "");
                        }
                        if (j == 9) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getReqDeptNa()) ? m.getReqDeptNa() : "");
                        }
                        if (j == 10) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getReqNo()) ? m.getReqNo() : "");
                        }
                        if (j == 11) {
                            String patType = "";
                            if ("1".equals(m.getPatType())) {
                                patType = "门诊";
                            }
                            if ("2".equals(m.getPatType())) {
                                patType = "急诊";
                            }
                            if ("3".equals(m.getPatType())) {
                                patType = "住院";
                            }
                            if ("4".equals(m.getPatType())) {
                                patType = "体检";
                            }
                            dataCell1.setCellValue(StringUtils.isNotBlank(patType) ? patType : "");
                        }
                        if (j == 12) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getSampleNo()) ? m.getSampleNo() : "");
                        }
                        if (j == 13) {
                            if (BeanUtil.isNotEmpty(m.getTestTime())) {
                                Timestamp timestamp = new Timestamp(m.getTestTime().getTime());
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                String formattedDate = sdf.format(timestamp);
                                dataCell1.setCellValue(BeanUtil.isNotEmpty(formattedDate) ? formattedDate : "");
                            } else {
                                dataCell1.setCellValue("");
                            }
                        }
                        if (j == 14) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getPrintDoctorNa()) ? m.getPrintDoctorNa() : "");
                        }
                        if (j == 15) {
                            if (BeanUtil.isNotEmpty(m.getPrintTime())) {
                                Timestamp timestamp = new Timestamp(m.getPrintTime().getTime());
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                String formattedDate = sdf.format(timestamp);
                                dataCell1.setCellValue(StringUtils.isNotBlank(formattedDate) ? formattedDate : "");
                            } else {
                                dataCell1.setCellValue("");
                            }
                        }
                        if (j == 16) {
                            int cs = 0;
                            if (BeanUtil.isNotEmpty(m.getPrintCount())) {
                                cs = m.getPrintCount().intValue();
                            }
                            dataCell1.setCellValue(BeanUtil.isNotEmpty(cs) ? Integer.toString(cs) : "");
                        }
                        if (j == 17) {
                            String itemNoNa = "";
                            if (StringUtils.isNotBlank(m.getItemNo())) {
                                itemNoNa += m.getItemNo();
                            }
                            if (StringUtils.isNotBlank(m.getItemNa())) {
                                itemNoNa += m.getItemNa();
                            }
                            dataCell1.setCellValue(StringUtils.isNotBlank(itemNoNa) ? itemNoNa : "");
                        }
                        if (j == 18) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getResult()) ? m.getResult() : "");
                        }
                        if (j == 19) {
                            String flg = "";
                            if (StringUtils.isNotBlank(m.getResultFlag())) {
                                if ("H".equals(m.getResultFlag())) {
                                    flg = "↑";
                                }
                                if ("L".equals(m.getResultFlag())) {
                                    flg = "↓";
                                }
                                if ("P".equals(m.getResultFlag())) {
                                    flg = "+";
                                }
                                if ("Q".equals(m.getResultFlag())) {
                                    flg = "±";
                                }
                                if ("N".equals(m.getResultFlag())) {
                                    flg = "-";
                                }
                                if ("E".equals(m.getResultFlag())) {
                                    flg = "×";
                                }
                            }
                            dataCell1.setCellValue(StringUtils.isNotBlank(flg) ? flg : "");
                        }
                        if (j == 20) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getRef()) ? m.getRef() : "");
                        }
                        if (j == 21) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getUnit()) ? m.getUnit() : "");
                        }
                    }
                    i++;
                }
                /*for (Map.Entry<String, List<LabMaininfo>> mm : maps.entrySet()) {
                    List<LabMaininfo> lstArr = mm.getValue();
                    if (lstArr != null || !lstArr.isEmpty()) {
                        List<LabMaininfo> lstArray = lstArr.stream().sorted(Comparator.comparing(LabMaininfo::getSeq, Comparator.nullsLast(Comparator.naturalOrder()))).collect(Collectors.toList());

                    }
                }*/

            }

            Map<String, List<int[]>> rowSpans = findStartEndIndices(list);
            for (Map.Entry<String, List<int[]>> entry : rowSpans.entrySet()) {
                // System.out.println("ID: " + entry.getKey() + " -> Indices: " + entry.getValue());
                try {
                    for (int j = 0; j < 17; j++) {
                        List<int[]> indices = entry.getValue();
                        CellRangeAddress cra = new CellRangeAddress(indices.get(0)[0] + 1, indices.get(0)[1] + 1, j, j);
                        sheet.addMergedRegion(cra);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=测试.xls");

            // 保存文件
            try (ServletOutputStream fileOut = response.getOutputStream()) {
                workbook.write(fileOut);
                fileOut.flush();
                System.out.println("Excel文件导出成功！");
            } catch (Exception e) {
                // e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (BeanUtil.isNotEmpty(workbook)) workbook.close();
            } catch (Exception ee) {
                ee.printStackTrace();
            }
        }

    }

    public void ExportExcelBac(ReportExportExcelParam reportExportExcelParam, HttpServletResponse response) throws IOException {

        String idsStr = reportExportExcelParam.getIds().isEmpty() ? "!@#QWE!@#" : reportExportExcelParam.getIds().stream().collect(Collectors.joining("','"));

        MPJLambdaWrapper<LabMaininfo> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabMaininfo.class);
        queryWrapper.eq(LabMaininfo::getDelFlag, 0);
        queryWrapper.selectAs("rptresult", LabRptresultQ::getItemNa, LabMaininfo::getItemNa);
        queryWrapper.selectAs("rptresult", LabRptresultQ::getItemNo, LabMaininfo::getItemNo);
        queryWrapper.selectAs("rptresult", LabRptresultQ::getTestResult, LabMaininfo::getResult);
        queryWrapper.selectAs("rptresult", LabRptresultQ::getResultFlag, LabMaininfo::getResultFlag);
        queryWrapper.selectAs("rptresult", LabRptresultQ::getRef, LabMaininfo::getRef);
        queryWrapper.selectAs("itemdict", LabItemDict::getUnit, LabMaininfo::getUnit);
        queryWrapper.selectAs("itemdict", LabItemDict::getSeq, LabMaininfo::getSeq);
        queryWrapper.selectAs("reqDept", SysOrgDepartment::getName, LabMaininfo::getReqDeptNa);
        queryWrapper.selectAs("printDocter", SysUser::getRealname, LabMaininfo::getPrintDoctorNa);
        queryWrapper.selectAs("rptgptna", LabRptGroup::getRptGroupName, LabMaininfo::getRptGroupNa);
        queryWrapper.selectAs(LabSampleType::getSampleTypeName, LabMaininfo::getSampleTypeNa);
        // queryWrapper.in(LabMaininfo::getId, ids);
        queryWrapper.inSql(LabMaininfo::getId, "select ID from LAB_MAININFO where ID in ('" + idsStr + "')");
        queryWrapper.leftJoin(LabRptresultQ.class, "rptresult", p -> p.eq(LabMaininfo::getSampleNo, LabRptresultQ::getSampleNo).isNotNull(LabRptresultQ::getSampleNo).ne(LabRptresultQ::getSampleNo, "").eq(LabMaininfo::getSampleda, LabRptresultQ::getSampleda).isNotNull(LabRptresultQ::getSampleda).eq(LabMaininfo::getRptGroup, LabRptresultQ::getRptGroup).isNotNull(LabRptresultQ::getRptGroup).ne(LabRptresultQ::getRptGroup, "").eq(LabRptresultQ::getDelFlag, 0));
        queryWrapper.leftJoin(LabItemDict.class, "itemdict", p -> p.eq(LabRptresultQ::getRptGroup, LabItemDict::getRptGroup).eq(LabRptresultQ::getItemNo, LabItemDict::getItemNo).isNotNull(LabItemDict::getRptGroup).isNotNull(LabItemDict::getItemNo).ne(LabItemDict::getRptGroup, "").ne(LabItemDict::getItemNo, "").eq(LabItemDict::getDelFlag, 0));
        queryWrapper.leftJoin(LabRptGroup.class, "rptgptna", p -> p.eq(LabMaininfo::getRptGroup, LabRptGroup::getRptGroup).eq(LabRptGroup::getDelFlag, 0).isNotNull(LabRptGroup::getRptGroup).ne(LabRptGroup::getRptGroup, ""));
        queryWrapper.leftJoin(SysOrgDepartment.class, "reqDept", p -> p.eq(LabMaininfo::getReqDept, SysOrgDepartment::getCode).eq(SysOrgDepartment::getDelFlag, 0).isNotNull(SysOrgDepartment::getCode).ne(SysOrgDepartment::getCode, ""));
        queryWrapper.leftJoin(SysUser.class, "printDocter", p -> p.eq(LabMaininfo::getPrintDoctor, SysUser::getUsername).eq(SysUser::getDelFlag, 0).isNotNull(SysUser::getUsername).ne(SysUser::getUsername, ""));
        queryWrapper.leftJoin(LabSampleType.class, p -> p.eq(LabMaininfo::getSampleType, LabSampleType::getSampleTypeCode));
        queryWrapper.ne(LabRptGroup::getBusinessType, "20");
        List<LabMaininfo> list1 = labMaininfoMapper.selectList(queryWrapper);
        List<LabMaininfo> bacMainInfoList = getBacMainInfoList(idsStr);
        list1.addAll(bacMainInfoList);
        List<LabMaininfo> list = list1.stream().sorted(Comparator.comparing(LabMaininfo::getId, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getSampleNo, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabMaininfo::getSeq, Comparator.nullsLast(Comparator.naturalOrder()))).collect(Collectors.toList());
        List<LabMaininfoExcel> excelList = BeanUtil.copyToList(list, LabMaininfoExcel.class);
        LabMaininfoExcel labMaininfoExcel1 = new LabMaininfoExcel();
        excelList.add(labMaininfoExcel1);
        for (LabMaininfoExcel labMaininfoExcel : excelList) {
            if (StringUtils.isNotBlank(labMaininfoExcel.getSampleda())){
                String sampleda = labMaininfoExcel.getSampleda();
                labMaininfoExcel.setSampleda(sampleda.substring(0, 10));
            }
            if (StringUtils.isNotBlank(labMaininfoExcel.getSex())){
                labMaininfoExcel.setSex(sexMap.get(labMaininfoExcel.getSex()));
            }
            if (StringUtils.isNotBlank(labMaininfoExcel.getAge())&&StringUtils.isNotBlank(labMaininfoExcel.getAgeUnit())){
                labMaininfoExcel.setAge(labMaininfoExcel.getAge() + labMaininfoExcel.getAgeUnit());
            }
            if (StringUtils.isNotBlank(labMaininfoExcel.getTestTime())){
                String testTime = labMaininfoExcel.getTestTime();
                labMaininfoExcel.setTestTime(testTime.substring(0, 10));
            }
            if (StringUtils.isNotBlank(labMaininfoExcel.getPrintTime())){
                String printTime = labMaininfoExcel.getPrintTime();
                labMaininfoExcel.setPrintTime(printTime.substring(0, 10));
            }
            if (StringUtils.isNotBlank(labMaininfoExcel.getResultFlag())){
                labMaininfoExcel.setResultFlag(flagMap.get(labMaininfoExcel.getResultFlag()));
            }

        }

        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("报告查询", "UTF-8"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");

        // ✅ 再写入数据
        try {
            EasyExcel.write(response.getOutputStream())
                    .head(LabMaininfoExcel.class)
                    .sheet()
                    .doWrite(excelList);
        } catch (Exception e) {
            // 可选：捕获异常并记录日志
            throw new IOException("导出Excel失败", e);
        }
    }
    public List<LabMaininfo> getBacMainInfoList(String idsStr) {

        MPJLambdaWrapper<LabMaininfo> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabMaininfo.class);
        queryWrapper.eq(LabMaininfo::getDelFlag, 0);
        queryWrapper.selectAs("bacResult", BacTestResult::getGermNa, LabMaininfo::getItemNa);
        queryWrapper.selectAs("bacResult", BacTestResult::getGermNo, LabMaininfo::getItemNo);
        queryWrapper.selectAs("reqDept", SysOrgDepartment::getName, LabMaininfo::getReqDeptNa);
        queryWrapper.selectAs("printDocter", SysUser::getRealname, LabMaininfo::getPrintDoctorNa);
        queryWrapper.selectAs("rptgptna", LabRptGroup::getRptGroupName, LabMaininfo::getRptGroupNa);
        // queryWrapper.in(LabMaininfo::getId, ids);
        queryWrapper.inSql(LabMaininfo::getId, "select ID from LAB_MAININFO where ID in ('" + idsStr + "')");
        queryWrapper.leftJoin(BacTestResult.class, "bacResult", p -> p.eq(BacTestResult::getRptGroup, LabMaininfo::getRptGroup).eq(BacTestResult::getSampleda, LabMaininfo::getSampleda).eq(BacTestResult::getSampleNo, LabMaininfo::getSampleNo).eq(BacTestResult::getDelFlag, 0));
        queryWrapper.leftJoin(LabRptGroup.class, "rptgptna", p -> p.eq(LabMaininfo::getRptGroup, LabRptGroup::getRptGroup).eq(LabRptGroup::getDelFlag, 0).isNotNull(LabRptGroup::getRptGroup).ne(LabRptGroup::getRptGroup, ""));
        queryWrapper.leftJoin(SysOrgDepartment.class, "reqDept", p -> p.eq(LabMaininfo::getReqDept, SysOrgDepartment::getCode).eq(SysOrgDepartment::getDelFlag, 0).isNotNull(SysOrgDepartment::getCode).ne(SysOrgDepartment::getCode, ""));
        queryWrapper.leftJoin(SysUser.class, "printDocter", p -> p.eq(LabMaininfo::getPrintDoctor, SysUser::getUsername).eq(SysUser::getDelFlag, 0).isNotNull(SysUser::getUsername).ne(SysUser::getUsername, ""));
        queryWrapper.eq(BacTestResult::getBacPublishStatus, 1);
        queryWrapper.eq(LabRptGroup::getBusinessType, "20");
        List<LabMaininfo> list1 = labMaininfoMapper.selectList(queryWrapper);
        return list1;
    }

    public void megerCellRow(List<LabMaininfo> list, Sheet sheet, Integer colF, Integer colE) {

        /*for (Map.Entry<String, List<int[]>> entry : rowSpans.entrySet()) {
            //System.out.println("ID: " + entry.getKey() + " -> Indices: " + entry.getValue());
            List<int[]> indices = entry.getValue();
            CellRangeAddress cra = new CellRangeAddress(indices.get(0)[0] + 1, indices.get(0)[1] + 1, colF, colE);
            sheet.addMergedRegion(cra);
        }*/
    }

    public Map<String, List<int[]>> findStartEndIndices(List<LabMaininfo> items) {
        Map<String, List<int[]>> indexMap = new HashMap<>();
        int n = items.size();

        for (int i = 0; i < n; i++) {
            System.out.println("==============================循环开始========================");
            String id = items.get(i).getId();
            if (!indexMap.containsKey(id)) {
                indexMap.put(id, new ArrayList<>());
            }

            // 如果是第一个元素或与前一个元素不同，则记录起始索引
            if (i == 0) {
                int startIndex = i;

                System.out.println("当前1:" + items.get(i).getId() + ",后一个：" + items.get(i + 1).getId() + "");
                // 查找终止索引
                while (i < n - 1 && items.get(i).getId().equals(items.get(i + 1).getId())) {
                    System.out.println("索引变化:" + i);
                    i++;
                }
                int endIndex = i;

                indexMap.get(id).add(new int[]{startIndex, endIndex});
            }
            if (i > 0 && !items.get(i).getId().equals(items.get(i - 1).getId())) {
                System.out.println("当前:" + items.get(i).getId() + ",前一个：" + items.get(i - 1).getId() + "");
                int startIndex = i;

                System.out.println("当前1:" + items.get(i).getId() + ",后一个：" + items.get(i + 1).getId() + "");
                // 查找终止索引
                while (i < n - 1 && items.get(i).getId().equals(items.get(i + 1).getId())) {
                    System.out.println("索引变化:" + i);
                    i++;
                }
                int endIndex = i;

                indexMap.get(id).add(new int[]{startIndex, endIndex});
            }
            System.out.println("==============================循环结束========================");
        }

        return indexMap;
    }


    public void bak(HttpServletResponse response) {
        HSSFWorkbook workbook = null;
        try {// new FileOutputStream("custom_format_excel.xlsx")) {
            workbook = new HSSFWorkbook();
            // 创建工作表
            Sheet sheet = workbook.createSheet("码农研究僧的博客");

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            // 创建第0列，其赋值为Cell类
            for (int i = 0; i < 22; i++) {
                Cell headerCell1 = headerRow.createCell(i);
                // 通过该类赋值其含义，此为第0列的属性
                if (i == 0) {
                    headerCell1.setCellValue("报告单元");
                }
                if (i == 1) {
                    headerCell1.setCellValue("检验日期");
                }
                if (i == 2) {
                    headerCell1.setCellValue("姓名");
                }
                if (i == 3) {
                    headerCell1.setCellValue("性别");
                }
                if (i == 4) {
                    headerCell1.setCellValue("年龄");
                }
                if (i == 5) {
                    headerCell1.setCellValue("病历号");
                }
                if (i == 6) {
                    headerCell1.setCellValue("申请目的");
                }
                if (i == 7) {
                    headerCell1.setCellValue("样本类型");
                }
                if (i == 8) {
                    headerCell1.setCellValue("科室");
                }
                if (i == 9) {
                    headerCell1.setCellValue("条码号");
                }
                if (i == 10) {
                    headerCell1.setCellValue("病人类型");
                }
                if (i == 11) {
                    headerCell1.setCellValue("标本号");
                }
                if (i == 12) {
                    headerCell1.setCellValue("上机时间");
                }
                if (i == 13) {
                    headerCell1.setCellValue("打印人");
                }
                if (i == 14) {
                    headerCell1.setCellValue("打印时间");
                }
                if (i == 15) {
                    headerCell1.setCellValue("打印次数");
                }
                if (i == 16) {
                    headerCell1.setCellValue("检验项目");
                }
                if (i == 17) {
                    headerCell1.setCellValue("检验结果");
                }
                if (i == 18) {
                    headerCell1.setCellValue("");
                }
                if (i == 19) {
                    headerCell1.setCellValue("参考范围");
                }
                if (i == 20) {
                    headerCell1.setCellValue("单位");
                }
            }
            // Cell headerCell1 = headerRow.createCell(0);
            // 通过该类赋值其含义，此为第0列的属性
            // headerCell1.setCellValue("Name");
            // 此为第1列的属性
            // Cell headerCell2 = headerRow.createCell(1);
            // headerCell2.setCellValue("Age");

            List<String> ids = new ArrayList<>();
            ids.add("1838381332784103425");
            ids.add("1838385530846199809");

            MPJLambdaWrapper<LabMaininfo> queryWrapper = new MPJLambdaWrapper<>();
            queryWrapper.selectAll(LabMaininfo.class);
            queryWrapper.eq(LabMaininfo::getDelFlag, 0);
            queryWrapper.selectAs("rptresult", LabRptresult::getItemNa, LabMaininfo::getItemNa);
            queryWrapper.selectAs("rptresult", LabRptresult::getTestResult, LabMaininfo::getResult);
            queryWrapper.selectAs("rptresult", LabRptresult::getResultFlag, LabMaininfo::getResultFlag);
            queryWrapper.selectAs("rptresult", LabRptresult::getRef, LabMaininfo::getRef);
            queryWrapper.selectAs("itemdict", LabItemDict::getUnit, LabMaininfo::getUnit);
            queryWrapper.selectAs("itemdict", LabItemDict::getSeq, LabMaininfo::getSeq);
            queryWrapper.in(LabMaininfo::getId, ids);
            queryWrapper.leftJoin(LabRptresult.class, "rptresult", p -> p.eq(LabMaininfo::getSampleNo, LabRptresult::getSampleNo).isNotNull(LabRptresult::getSampleNo).ne(LabRptresult::getSampleNo, "").eq(LabMaininfo::getSampleda, LabRptresult::getSampleda).isNotNull(LabRptresult::getSampleda).eq(LabMaininfo::getRptGroup, LabRptresult::getRptGroup).isNotNull(LabRptresult::getRptGroup).ne(LabRptresult::getRptGroup, "").eq(LabRptresult::getDelFlag, 0));
            queryWrapper.leftJoin(LabItemDict.class, "itemdict", p -> p.eq(LabRptresult::getRptGroup, LabItemDict::getRptGroup).eq(LabRptresult::getItemNo, LabItemDict::getItemNo).isNotNull(LabItemDict::getRptGroup).isNotNull(LabItemDict::getItemNo).ne(LabItemDict::getRptGroup, "").ne(LabItemDict::getItemNo, "").eq(LabItemDict::getDelFlag, 0));
            List<LabMaininfo> list = labMaininfoMapper.selectList(queryWrapper);

            if (!list.isEmpty()) {
                int i = 1;
                for (LabMaininfo m : list) {
                    Row dataRow1 = sheet.createRow(i);
                    for (int j = 0; j < 22; j++) {
                        Cell dataCell1 = dataRow1.createCell(j);
                        if (j == 0) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getRptGroupNa()) ? m.getRptGroupNa() : "");
                        }
                        if (j == 1) {
                            dataCell1.setCellValue("2024-05-01");// StringUtils.isNotBlank(m.getSampleda()) ? m.getSampleda() : "");
                        }
                        if (j == 2) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getPatNa()) ? m.getPatNa() : "");
                        }
                        if (j == 3) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getSex()) ? m.getSex() : "");
                        }
                        if (j == 4) {
                            dataCell1.setCellValue("66岁");// StringUtils.isNotBlank(m.getAge()) ? m.getAge() : "");
                        }
                        if (j == 5) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getPatNo()) ? m.getPatNo() : "");
                        }
                        if (j == 6) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getReqPurpose()) ? m.getReqPurpose() : "");
                        }
                        if (j == 7) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getSampleTypeNa()) ? m.getSampleTypeNa() : "");
                        }
                        if (j == 8) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getReqDeptNa()) ? m.getReqDeptNa() : "");
                        }
                        if (j == 9) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getReqNo()) ? m.getReqNo() : "");
                        }
                        if (j == 10) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getPatTypeNa()) ? m.getPatTypeNa() : "");
                        }
                        if (j == 11) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getSampleNo()) ? m.getSampleNo() : "");
                        }
                        if (j == 12) {
                            dataCell1.setCellValue("2024-05-01 11:25");// BeanUtil.isNotEmpty(m.getTestTime()) ? m.getTestTime() : "");
                        }
                        if (j == 13) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getPrintDoctorNa()) ? m.getPrintDoctorNa() : "");
                        }
                        if (j == 14) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getPrintDoctorNa()) ? m.getPrintDoctorNa() : "");
                        }
                        if (j == 15) {
                            dataCell1.setCellValue("3");// StringUtils.isNotBlank(m.getPrintCount()) ? m.getPrintCount().toString() : "");
                        }
                        if (j == 16) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getItemNa()) ? m.getItemNa() : "");
                        }
                        if (j == 17) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getResult()) ? m.getResult() : "");
                        }
                        if (j == 18) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getResultFlag()) ? m.getResultFlag() : "");
                        }
                        if (j == 19) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getRef()) ? m.getRef() : "");
                        }
                        if (j == 20) {
                            dataCell1.setCellValue(StringUtils.isNotBlank(m.getUnit()) ? m.getUnit() : "");
                        }
                        // dataCell1.setCellValue("码农");
                    }
                    i++;
                }
            }

            // 添加第一行的数据行
            /*Row dataRow1 = sheet.createRow(1);
            Cell dataCell1 = dataRow1.createCell(0);
            dataCell1.setCellValue("码农");
            Cell dataCell2 = dataRow1.createCell(1);
            dataCell2.setCellValue(25);*/

            // 添加第二行的数据行
            /*Row dataRow2 = sheet.createRow(2);
            Cell dataCell3 = dataRow2.createCell(0);
            dataCell3.setCellValue("研究僧");
            Cell dataCell4 = dataRow2.createCell(1);
            dataCell4.setCellValue(50);*/

            // response.setHeader("Content-Type", "application/msexcel");
            // response.setContentType("application/vnd.ms-excel;charset=utf-8");
            // response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("测试.xls", "utf-8"));

            /*response.setHeader("Content-Disposition", "attachment;");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("utf-8");*/

            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=测试.xls");

            // 保存文件
            try (ServletOutputStream fileOut = response.getOutputStream()) {
                workbook.write(fileOut);
                fileOut.flush();
                System.out.println("Excel文件导出成功！");
            } catch (Exception e) {
                // e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (BeanUtil.isNotEmpty(workbook)) workbook.close();
            } catch (Exception ee) {
                ee.printStackTrace();
            }
        }
    }
}
